package com.wan.activity;

import java.util.HashMap;

import net.sourceforge.simcpux.Util;

import com.reyun.sdk.ReYunTrack;
import com.wan.activity.util.EditTextFocusLintener;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.HttpUtils;
import com.wan.commonsdk.WanCommonSdk;
import com.wan.commonsdk.WanServerResposeCode;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
//------------------------------------------------------------------------
//
// 用户注册
//
//------------------------------------------------------------------------
public class RegesterActivity extends BaseActivity implements OnClickListener
{
	private final int REGESTER_SUCCESS = WanServerResposeCode.WAN_REGESTER_SUCCESS;
	private final int REGESTER_FAILURE = WanServerResposeCode.WAN_REGESTER_FAILURE;
	private final int NETWORK_ERROR = 10086;
	private final int REGESTER_NORMAL	=	1;
	private final String url = "";
	private Button btn_reg_regester;
	private TextView reg_back_btn;
	private EditText et_username, et_password;
	private Activity activity;
	private Thread mThread;
	private String username, password,status;
	private String commend;
	private TextView reg_to_phone_reg;
	private CheckBox cb_reg_agree;
	
	private Button reg_un_edclose,reg_pw_edclose;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		if (WanCommonSdk.screen_orientation == WanCommonSdk.SCREEN_ORIENTATION_PORTRAIT)
		{
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		else
		{
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("wan51_regest_activity", "layout")); 
		activity = this;

		this.btn_reg_regester = (Button) findViewById(Util.getResID("btn_reg_regester", "id"));

		btn_reg_regester.setOnClickListener(this);
		Conet conet = Conet.getInstance();
		conet.addActivity(this);
		reg_back_btn = (TextView) findViewById(Util.getResID("reg_back_btn", "id"));
//		
		reg_back_btn.setOnClickListener(this);
		this.et_username = (EditText) findViewById(Util.getResID("et_reg_username", "id"));
		
		this.et_password = (EditText) findViewById(Util.getResID("et_reg_password", "id"));
		
		reg_to_phone_reg = (TextView) findViewById(Util.getResID("reg_to_phone_reg", "id"));
		reg_to_phone_reg.setText(Html.fromHtml("<u>"+"使用手机号注册"+"</u>"));
		reg_to_phone_reg.setOnClickListener(this);
		
		reg_un_edclose = (Button) findViewById(Util.getResID("reg_un_edclose", "id"));
		reg_pw_edclose = (Button) findViewById(Util.getResID("reg_pw_edclose", "id"));
		
		et_username.setOnFocusChangeListener(new EditTextFocusLintener(et_username, reg_un_edclose));
		et_password.setOnFocusChangeListener(new EditTextFocusLintener(et_password, reg_pw_edclose));
//		checkbox.isChecked(); checkbox.setChecked(true|false);
		cb_reg_agree = (CheckBox) findViewById(Util.getResID("cb_reg_agree", "id"));
		cb_reg_agree.setOnClickListener(this);
	}
	


	//------------------------------------------------------------------------
	//
	// 消息处理
	//
	//------------------------------------------------------------------------
	private Handler mHandler = new Handler() 
	{  
        public void handleMessage (Message msg) 
        {
            switch(msg.what) 
            {  
            case REGESTER_SUCCESS:   
            	
            	hideLoading();
            	// 注册成功的回调
            	
            	
            	/*TrackingIO.setRegisterWithAccountID(Conet.mUserInfo.getUser_id());
            	
            	
            	TrackingIO.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());*/
            	
            	ReYunTrack.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());
            	ReYunTrack.setRegisterWithAccountID(Conet.mUserInfo.getUser_id());
            	WanCommonSdk.loginCallBack.loginSuccess(
						Conet.mUserInfo.getUser_id(),
						Conet.mUserInfo.getAccess_token());
            	Conet.getInstance().exit();
            	finish();
            	
                break;  
  
            case REGESTER_FAILURE:  
            	hideLoading();
				showHint(activity.getString(Util.getResID("login_error_hint", "string")));
                mThread = null;
                break; 
            case WanServerResposeCode.WAN_REGESTER_WRONG_USERNAME:
            	hideLoading();
				showHint("用户名已被使用"); 
                mThread = null;
                break;
            case WanServerResposeCode.WAN_REGESTER_WRONG_PASSWORD:
            	hideLoading();
				showHint(activity.getString(Util.getResID("reg_password_hint", "string"))); 
                mThread = null;
                break;
            case WanServerResposeCode.WAN_HAS_ACCOUNT:
            	hideLoading();
            	if (commend != null) et_username.setText(commend);
				showHint(activity.getString(Util.getResID("has_account_hint", "string")));  
                mThread = null;
                break;
            case NETWORK_ERROR:
            	hideLoading();
				showHint(activity.getString(Util.getResID("newwork_error", "string")));  
            	mThread = null;
            	break;
				default:
					hideLoading();
					showToast(status);
					mThread = null;
					break;
            }
        }
    };

	//------------------------------------------------------------------------
	//
	// 线程处理
	//
	//------------------------------------------------------------------------

	Runnable runnable = new Runnable()
	{

		@Override
		public void run()
		{
			HashMap<String, String> result = HttpUtils.HttpReg(username, password);
			if (result == null)
			{
				mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
				return;
			}
			else if(result.get("status").equals(String.valueOf(REGESTER_SUCCESS)))
			{
				//UserInfo userInfo = new UserInfo();
				Conet.mUserInfo.setUser_name(username);
				Conet.mUserInfo.setUser_password(password);
				Conet.mUserInfo.setUser_id(result.get("user_id"));
				Conet.mUserInfo.setAccess_token(result.get("access_token"));
				
				Conet.mUserInfo.setGuest(false);
				mHandler.obtainMessage(REGESTER_SUCCESS, Conet.mUserInfo).sendToTarget();

				return;
			} else if (result.get("status").equals(String.valueOf(WanServerResposeCode.WAN_HAS_ACCOUNT)))
			{
				commend = result.get("commend");
			}
			status	=	result.get("status").toString();
			mHandler.obtainMessage(Integer.parseInt(result.get("status"))).sendToTarget();
		}
	};


	//------------------------------------------------------------------------
	//
	// 事件处理
	//
	//------------------------------------------------------------------------
	@Override
	public void onClick(View v) 
	{
		// TODO Auto-generated method stub
		if(v.getId() == Util.getResID("btn_reg_regester", "id"))  
		{ if(cb_reg_agree.isChecked()){
			if(!checkUserInfo())
				return;
			username = this.et_username.getText().toString();
			password = this.et_password.getText().toString();
			showLoading("注册中");  
			String ss = this.getString(Util.getResID("reg_loading_hint", "string"));
			mThread = new Thread(runnable);
			mThread.start();
			}else{
				Toast.makeText(Conet.mActivity, "需同意平台协议", Toast.LENGTH_SHORT).show();
			}
		} else if (v.getId() == Util.getResID("btn_login", "id")){  
			Log.d("51wan", "-------------");
			Intent intent = new Intent(this, LoginActivity.class);
			if(Conet.mUserInfo.getUser_name()!=null && Conet.mUserInfo.getUser_password()!=null){
				intent.putExtra("username", Conet.mUserInfo.getUser_name());
				intent.putExtra("password", Conet.mUserInfo.getUser_password());
			}
			activity.startActivity(intent);
			this.finish();
		}else if(v.getId() == Util.getResID("reg_back_btn", "id")){   
			finish();
		}else if(v.getId() == Util.getResID("reg_to_phone_reg", "id")){
			
			Intent intent = new Intent(RegesterActivity.this,WanPhoneRegesterActivity.class);
			startActivity(intent);
		}else if(v.getId() == Util.getResID("cb_reg_agree", "id")){
			if(cb_reg_agree.isChecked()){
				cb_reg_agree.setChecked(true);
			}else{
				cb_reg_agree.setChecked(false);
			}
		}
//		else if(v.getId() == R.id.btn_reg_close) 
//		{
//			Intent intent = new Intent(this, LoginActivity.class);
//			this.startActivity(intent);
//			this.finish();
//		}
		
	}
	
	private Boolean checkUserInfo()
	{
		String str_pw = this.et_password.getText().toString();
		
		int un_length = this.et_username.getText().toString().length();
		int pw_length = str_pw.length();
		
		if (un_length == 0 || pw_length == 0)
		{
			showHint("用户名和密码不能为空");
			return false;
		}
		
		if (un_length < WanCommonSdk.MIN_USERNAME_LENGTH || un_length > WanCommonSdk.MAX_USERNAME_LENGTH)
		{
			showHint(this.getString(Util.getResID("username_length_hint", "string")));  
			return false;
     	}
		if (pw_length < WanCommonSdk.MIN_PASSWORD_LENGTH || pw_length > WanCommonSdk.MAX_PASSWORD_LENGTH)
		{
			showHint(this.getString(Util.getResID("password_length_hint", "string")));  
			return false;
		}
		
		
		return true;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {  
//        	Intent intent = new Intent(this, LoginActivity.class);
//			this.startActivity(intent);
			this.finish();
            return true;
        } else  
            return super.onKeyDown(keyCode, event);  
    }  



}
